package com.jereh.topnews.demo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jereh.topnews.R;
import com.jereh.topnews.entity.Content;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class NetWorkActivity extends AppCompatActivity {

    private TextView title;
    private TextView content;
    //接口地址
    private static final String httpUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";
    //传参信息
    private static final String httpArg = "channelId=5572a109b3cdc86cf39001db&channelName=%E5%9B%BD%E5%86%85%E6%9C%80%E6%96%B0&title=%E4%B8%8A%E5%B8%82&page=1&needContent=1&needHtml=0";
    //数据来源
    private List<Content> list=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_work);
        title=(TextView)findViewById(R.id.title);
        content=(TextView)findViewById(R.id.content);
        new HttpAsyncTask().execute(httpUrl,httpArg);
    }

    public static void main(String[] args){
//        System.out.println(request(httpUrl, httpArg));
        String jsonResult=request(httpUrl,httpArg);
        JSONObject object = JSON.parseObject(jsonResult);
        JSONObject body = (JSONObject) object.get("showapi_res_body");
        JSONObject pagebean = (JSONObject)body.get("pagebean");
        JSONArray contentlist=pagebean.getJSONArray("contentlist");
        List<Content> temp=JSON.parseArray(contentlist.toJSONString(), Content.class);
        for(Content content:temp){
            System.out.println(content);
        }
    }

    /**
     * 把json数据解析成对象
     * @param jsonResult
     */
    private void initData(String jsonResult){
//        String jsonResult=request(httpUrl,httpArg);
        JSONObject object = JSON.parseObject(jsonResult);
        JSONObject body = (JSONObject) object.get("showapi_res_body");
        JSONObject pagebean = (JSONObject)body.get("pagebean");
        JSONArray contentlist=pagebean.getJSONArray("contentlist");
        List<Content> temp=JSON.parseArray(contentlist.toJSONString(), Content.class);
        list.addAll(temp);
    }

    /**
     * @param httpUrl
     *            :请求接口
     * @param httpArg
     *            :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey",  "a52d8b4dfce6acab1649ad427584483d");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    class HttpAsyncTask extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... params) {
            return request(params[0],params[1]);
        }

        @Override
        protected void onPostExecute(String s) {
            initData(s);
            title.setText(list.get(0).getTitle());
            content.setText(list.get(0).getContent());
        }
    }
}
